In this practical we will write a simple function that simulates rolling one or more dice.
sample()The function sample allows us to draw values from a given set of values, with or without replacement.
It has arguments
x: a vector of values to draw fromsize: the number of values to drawreplace: can we choose the same element of x multiple times?prob: a vector of probability weights (by default all elements of x have equal probability to be drawn)Write the syntax to simulate a single role of a die using the function sample() (no function yet).
x and size.
Write your own function that simulates this one role of a die.
<function name> <- function ( <arguments> ) {<function body>}
Take another look at the description of the function sample(). How would you need to change the syntax from Task 1 from above to simulate rolling two dice?
size and you need to specify the argument replace.
sample().
## [1] 6 3
## [1] 2
## [1] 4 3 1 2 6 4 2 2 3 5
dice() without specifying the argument n?## [1] 3 4 1 3 3 6
By default, the function dice() will role 6 dice.
This is due to the behaviour of the function sample(). In the help file for sample() (run ?sample) we can read in the section Details:
For
samplethe default forsizeis the number of items inferred from the first argument, so thatsample(x)generates a random permutation of the elements ofx(or1:x).
What can we learn from this?
Re-write the function dice() so that by default only one die is used.
© Nicole Erler